
bt.module({builder: function(bt) {
    var j$ = jQuery;
    var map;
    var editMap;
    var marker;
    var currentPOI;
    var ADD_NEW_STR = "_sys_add_new_";
    var poiScroller;
    var new_poi_index = 0;

    var _refreshPOILocation = function(_map, target, saveCallback) {
        if(!_map.bteditable) {
            return;
        }
        var latLng = marker.getPosition();
        target.data("status", "get_geo");
        bt.gmap.convertCoordinateToGeo(latLng.lat(), latLng.lng(),
            function(country_code, country, province, city) {
                var text = ""
                    + jQuery.map([city, province, country],
                               function(x) {
                                   return x? x: null;
                               }).join(", ");
                text = j$.trim(text)? text: "位置";
                target.find(".location .text").html(text);
                target.addClass("unsaved");
                if(target.data("status") == "to_save") {
                    saveCallback();
                } else {
                    target.removeData("status");
                }
            }
        );
    };

    var _addMarker = function(lat, lng, _map, target, saveCallback) {
        if(marker) {
            marker.setMap(null);
            marker = null;
        }
        marker = bt.gmap.addMarker(_map, lat, lng);
        _refreshPOILocation(_map, target, saveCallback);
        if(_map.bteditable) {
            bt.gmap.addListener(marker, 'dragend', function() {
                _refreshPOILocation(_map, target, saveCallback);
            });
        } else {
            bt.gmap.setOptions(marker, {"draggable": false});
        }
    };

    var _hideAddPOIMap = function() {
        var popup = j$("#add-poi-popup");
        popup.find(".left-list").removeClass("disabled");
        popup.find(".left-list .search-text").css("opacity", 1);
        popup.find(".left-list .all-poi .result-item").css("opacity", 1);
        popup.find(".left-list .done").css("opacity", 1);
        // bt.gmap.closePOIInfowindow(); // 会造成地图变黑，显示地形地图
        popup.find(".right-map").fadeOut(function() {
            popup.css("width", "350px");
            popup.animate({left: popup.offset().left + 220});
        });
        if(marker) {
            marker.setMap(null);
        }
        j$('.right-map .pos-search input').val("");
        currentPOI.removeClass("current-poi");
        currentPOI = null;
    };

    var _saveCurrentPOI = function() {
        if(currentPOI.data("status") == "get_geo") {
            currentPOI.data("status", "to_save");
        } else {
            currentPOI.removeClass("unsaved")
                .removeData("status");
            currentPOI.data("item")["originalText"] = currentPOI.find(
                ".location .text").html();
            if(marker) {
                currentPOI.data("item")["lat"] = marker.getPosition().lat();
                currentPOI.data("item")["lng"] = marker.getPosition().lng();
            }
            _hideAddPOIMap();
        }
    };

    var _checkAllPhotosLinkedToPOI = function() {
        // Check whether all photos are linked to POI
        if(j$(".photo-panel .photos .unselected").length == 0) {
            j$(".photo-panel").addClass("empty");
        } else {
            j$(".photo-panel").removeClass("empty");
        }
    };

    var _updateLinkedPhotoCount = function(obj) {
        var count = j$(obj).data("photos").length;
        if(count > 0) {
            j$(".photo-count-mask-text span", obj).html(count);
            j$(".photo-count-mask", obj).show();
            j$(".photo-count-mask-text", obj).show();
        } else {
            j$(".photo-count-mask", obj).hide();
            j$(".photo-count-mask-text", obj).hide();
        }
    };

    var _addPhotoToPOI = function(droppable, draggable, imgUrl) {
        droppable.find(".default-image img").remove();
        droppable.find(".default-image")
            .append("<img src='" + imgUrl + "' alt='' />");
        droppable.find(".default-image img").load(function() {
            bt.misc.centerAlignImg(j$(this), 100, 100, false);
        });
        bt.misc.centerAlignImg(droppable.find(".default-image img"),
                               100, 100, false);
        draggable.fadeOut().removeClass("unselected");
        _checkAllPhotosLinkedToPOI();
        if(droppable.data("photos")) {
            droppable.data("photos").push(draggable.attr("id"));
        } else {
            droppable.data("photos", [draggable.attr("id")]);
        }
        _updateLinkedPhotoCount(droppable);
        j$(".photo-item").removeClass("dragged");
    };

    var _initPOIEvent = function(obj) {
        obj.droppable({
            accept: ".photo-item",
            hoverClass: "poi-item-drop-over",
            drop: function(e, ui) {
                var droppable = j$(this);
                var imgUrl;
                var draggable;
                var _container = ui.helper.children("li");
                j$.each(_container, function(index, val) {
                    var draggable = j$("#"+j$(val).attr("id"));
                    draggable.trigger("click");
                    imgUrl = j$(val).find(".photo img").attr("src");
                    _addPhotoToPOI(droppable, draggable, imgUrl);
                });
            }
        });
    };

    var _finishAddPOI = function() {
        j$("#add-poi-popup .all-poi .poi-list .result-item").each(function () {
            var newPOI = j$(".poi-panel .poi-item-tpl").clone();
            newPOI.removeClass("poi-item-tpl hidden")
                  .addClass(j$(this).data("item").meta + j$(this).data("item").type)
                  .data("type", j$(this).data("item").meta + j$(this).data("item").type)
                  .data("item", j$(this).data("item"))
                  .addClass(j$(this).data("is-new-poi")? "is-new-poi": "")
                  .prependTo(".poi-list");
            newPOI.attr("id", j$(this).attr("poi-id"));
            newPOI.find(".text span.ellipsis_text").html(
                j$(this).find(".name").text()).attr("title", j$(this).find(".name").text());
            newPOI.data("address", j$(this).find(".location .text").text());
            _initPOIEvent(newPOI);
            j$(this).remove();
            poiScroller.addItem();
            poiScroller.scrollTo(0, function() {
                ellipsisPOI(newPOI);
            });
        });
        j$("#add-poi-popup").parents("html").click();
        j$(".all-poi").addClass("empty");
    };

    var _initAddPOIPopupMapEvent = function() {
        if(!google) {
            return;
        }
        var myOptions = {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        map = bt.gmap.createMap("map", myOptions);
        bt.gmap.addListener(map, 'click', function(event) {
            if(!map.bteditable) {
                return;
            }
            _addMarker(event.latLng.lat(), event.latLng.lng(),
                map, currentPOI, _saveCurrentPOI);
        });
    };

    var _renderPOIItem = function(item) {
        var address = j$.trim(item.location);
        if(!address) {
            address = item.is_new? "添加位置": "位置";
        }
        var right = j$("<div class='right fl'></div>")
            .append("<p class='name one-row-ellipsis'>"
                    + item.label
                    + "</p>")
            .append("<div class='location'>"
                    + "<i class='icon fl'></i>"
                    + "<p class='text one-row-ellipsis fl'>"
                    + address
                    + "</p>"
                    + "</div>");
        var poiItem = j$("<li class='result-item " + item.meta + item.type + "'>")
            .append("<div class='icon-wrapper fl'><div class='icon'></div></div>")
            .append(right)
            .data("item", item);
        poiItem.attr("poi-id", item.is_new? "new" + item.id: item.id);
        return poiItem;
    };

    var ellipsisResultItem = function(obj) {
        var opts = {max_rows: 1, whole_word: false, allow_dangle: true};
        obj.find(".name").each(function() {
            j$(this).ThreeDots(opts);
        });
        obj.find(".location .text").each(function() {
            j$(this).ThreeDots(opts);
        });
        obj.find("li.text div.text").each(function() {
            j$(this).ThreeDots(opts);
        });
    };

    var ellipsisPOI = function(obj) {
        var opts = {max_rows: 2, whole_word: false, allow_dangle: true};
        obj.find(".text").each(function() {
            j$(this).ThreeDots(opts);
        });
    };

    var initAddPOIPopupEvent = function() {
        var popup = j$("#add-poi-popup");

        /*
         * AUTO_COMPLETE DATA STRUCTURE
         * {
         *     id: <ciphered ID>,
         *     meta: "[poi|place]"    # "type" ==> POI;
         *                             # "place" ==> City/Province/Country/Attraction;
         *     type: <type>,
         *     value: "<POI/Place name>",
         *     label: "<Displayed POI/Place name>",
         *     location: "<Address/Geo location>",
         *     lat: "<Latitude>",
         *     lng: "<Longitude>",
         * }
         */
        bt.gmap.initMapScript(_initAddPOIPopupMapEvent);

        popup.find(".auto-complete .result-item").live("click", function() {
            var item = j$(this);
            popup.find(".left-list .search-text .input input").autocomplete("close");
            j$(".all-poi .poi-list").show();
            item.clone().hide()
                .append("<div class='remove pa'></div>")
                .data("item", item.data("item"))
                .prependTo(".all-poi .poi-list")
                .slideDown();
            j$(".all-poi").removeClass("empty");
            popup.find(".left-list .search-text .input input").val("").blur();
        });

        popup.find(".auto-complete .add-new-item").live("click", function() {
            var item = _renderPOIItem({
                id: new_poi_index ++,
                value: j$(".auto-complete li.text div.text").attr("threedots"),
                label: j$(".auto-complete li.text div.text").attr("threedots"),
                location: "",
                type: j$(this).data("poi-type"),
                meta: "poi",
                is_new: true
            });
            popup.find(".left-list .search-text .input input").autocomplete("close");
            j$(".all-poi .poi-list").show();
            item.hide()
                .append("<div class='remove pa'></div>")
                .data("item", item.data("item"))
                .data("is-new-poi", true)
                .prependTo(".all-poi .poi-list")
                .slideDown(function() {
                    ellipsisResultItem(item);
                });
            j$(".all-poi").removeClass("empty");
            popup.find(".left-list .search-text .input input").val("").blur();
        });

        popup.find(".left-list .done").click(function() {
            _finishAddPOI();
        });

        popup.find(".right-map .cancel").click(function() {
            currentPOI.find(".location .text")
                .html(currentPOI.data("item")["originalText"]);
            currentPOI.removeClass("unsaved")
                .removeData("status");
            _hideAddPOIMap();
        });

        popup.find(".right-map .save").click(function() {
            _saveCurrentPOI();
        });

        popup.find(".all-poi .poi-list .result-item").live("click", function() {
            // Only new POI is editable
            map.bteditable = j$(this).data("item")["is_new"] || false;

            currentPOI = j$(this);
            currentPOI.addClass("current-poi");
            currentPOI.data("item")["originalText"] = currentPOI.find(
                ".location .text").html();
            var leftList = popup.find(".left-list");

            // Disable and fadeout left-list
            popup.find(".left-list").addClass("disabled");
            popup.find(".left-list .search-text").css("opacity", 0.5);
            popup.find(".left-list .all-poi .result-item").css("opacity", 0.5);
            popup.find(".left-list .done").css("opacity", 0.5);
            popup.find(".left-list .all-poi .current-poi").css("opacity", 1);

            popup.find(".right-map .selected-bt").css(
                "top", currentPOI.offset().top - leftList.offset().top - 12);
            popup.find(".right-map .selected-br").css(
                "top", currentPOI.offset().top - leftList.offset().top - 11);
            popup.find(".right-map .selected-bb").css(
                "top", currentPOI.offset().top - leftList.offset().top + 65);
            popup.find(".right-map .selected-bl").css(
                "top", currentPOI.offset().top - leftList.offset().top - 12);

            if(popup.find(".right-map").css("display") == "none") {
                popup.css("width", "812px");
                popup.animate({left: popup.offset().left - 220},
                    function() {
                        popup.find(".right-map").fadeIn(function() {
                            bt.gmap.refreshMap(map);
                            var info = currentPOI.data("item");
                            var address = j$(".right .name", currentPOI).text();
                            j$('.right-map .pos-search input').val(address);
                            if(info.lat && info.lng) {
                                bt.gmap.setZoom(map, 13);
                                bt.gmap.panTo(map, info.lat, info.lng);
                                _addMarker(info.lat, info.lng,
                                    map, currentPOI, _saveCurrentPOI);
                            } else {
                                j$('.right-map .pos-search input').blur();
                                if(j$.trim(address)) {
                                    marker = null;
                                    bt.gmap.zoomToWorld(map);
                                    bt.gmap.searchAddress(map, address, function(result) {
                                        if(!map.bteditable) {
                                            return;
                                        }
                                        var latLng= result[0].geometry.location;
                                        _addMarker(latLng.lat(), latLng.lng(), map, currentPOI, _saveCurrentPOI);
                                    });
                                }
                            }
                        });
                });
            }
        });

        popup.find(".all-poi .poi-list .result-item .remove")
            .live("click", function(e) {
                if(confirm("真的要删除这个拍照地点么？")) {
                    j$(this).parents(".result-item").slideUp(function() {
                        j$(this).remove();
                    });
                }
                e.stopPropagation();
            });

        popup.find(".left-list .search-text .input input").keydown(function(e) {
            var code = e.which;
            if (code == 13) {
                j$(this).autocomplete("search", j$(this).val());
                e.preventDefault();
            }
        });

        popup.find(".left-list .search-text .input input").autocomplete({
            delay: 500,
            appendTo: "#add-poi-popup .auto-complete",
            source: '/create_trip/poi_search_autocomplete/',
            response: function(e, ui) {
                ui.content.push({
                    label: ADD_NEW_STR,
                    value: ADD_NEW_STR
                    });
            },
            open: function(e, ui) {
                j$("#add-poi-popup .add-new>li").clone()
                    .appendTo(j$(this).autocomplete("widget"))
                    .show();
                j$(".auto-complete div.text span.ellipsis_text").text(
                    popup.find(".left-list .search-text .input input").val());
                ellipsisResultItem(j$(".auto-complete"));
            },
            close: function(e, ui) {
            }
        }).data("autocomplete")._renderItem = function(ul, item) {
            if(item.label == ADD_NEW_STR) {
                return j$("<li class='hidden'></li>");
            }
            var poiItem = _renderPOIItem(item).appendTo(ul);

            return poiItem;
        };

        var _searchAddress = function() {
            j$('.right-map .pos-search input').blur();
            var address = j$('.right-map .pos-search input').val();
            if(j$.trim(address)) {
                bt.gmap.searchAddress(map, address, function(result) {
                    if(!map.bteditable) {
                        return;
                    }
                    var latLng = result[0].geometry.location;
                    _addMarker(latLng.lat(), latLng.lng(), map, currentPOI, _saveCurrentPOI);
                });
            }
        };

        popup.find(".right-map .pos-search .search").click(function() {
            _searchAddress();
        });

        j$('.right-map .pos-search input').keydown(function(e) {
            var code = e.which;
            if (code == 13) {
                _searchAddress();
                e.preventDefault();
            }
        });
    };

    var _saveEditingPOI = function() {
        var popup = j$("#poi-edit-popup");
        var name = popup.find(".title input").val();
        var target = popup.find(".map-edit");

        currentPOI.find(".title .text .threedots_ellipsis").remove();
        currentPOI.find(".title .text span.ellipsis_text").html(name);
        currentPOI.find(".title .text").removeAttr("threedots")
            .ThreeDots({max_rows: 1, whole_word: false, allow_dangle: true});
        currentPOI.data("address", popup.find(".location .text").attr("threedots"));

        if(target.data("status") == "get_geo") {
            target.data("status", "to_save");
        } else {
            target.removeClass("unsaved").removeData("status");
            if(marker) {
                currentPOI.data("item")["lat"] = marker.getPosition().lat();
                currentPOI.data("item")["lng"] = marker.getPosition().lng();
            }
        }
    };

    var _initEditPOIPopupMapEvent = function() {
        if(!google) {
            return;
        }
        var myOptions = {
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        editMap = bt.gmap.createMap("poi-edit-map", myOptions);
        bt.gmap.addListener(editMap, 'click', function(event) {
            if(!editMap.bteditable) {
                return;
            }
            _addMarker(event.latLng.lat(), event.latLng.lng(),
                editMap, j$("#poi-edit-popup .map-edit"),
                _saveEditingPOI);
        });
    };

    var initEditPOIPopupEvent = function() {
        var popup = j$("#poi-edit-popup");

        var _searchAddress = function() {
            j$('.map-edit .pos-search input').blur();
            var address = j$('.map-edit .pos-search input').val();
            if(j$.trim(address)) {
                bt.gmap.searchAddress(editMap, address, function(result) {
                    if(!editMap.bteditable) {
                        return;
                    }
                    var latLng = result[0].geometry.location;
                    _addMarker(latLng.lat(), latLng.lng(),
                        editMap, j$("#poi-edit-popup .map-edit"),
                        _saveEditingPOI);
                });
            }
        };

        bt.gmap.initMapScript(_initEditPOIPopupMapEvent);

        popup.find(".map-edit .pos-search .search").click(function() {
            _searchAddress();
        });

        $('.map-edit .pos-search input').keydown(function(e) {
            var code = e.which;
            if (code == 13) {
                _searchAddress();
                e.preventDefault();
            }
        });

        popup.find(".done").click(function() {
            _saveEditingPOI();
            popup.dialog("close");
        });
    };

    var _collectNewPOIs = function(data) {
        var newPOIs = j$(".is-new-poi");
        var newPOIData = [];
        newPOIs.each(function() {
            var id = j$(this).attr("id");
            var name = j$(this).find(".text").attr("threedots");
            var type = j$(this).data("item").type;
            var lat = j$(this).data("item").lat;
            var lng = j$(this).data("item").lng;
            newPOIData.push([id, name, type, lat, lng]);
        });
        data["new_poi_count"] = newPOIs.length;
        data["new_poi_data"] = newPOIData;
    };

    var _collectLinkInfo = function(data) {
        var linkInfo = [];
        j$(".poi-panel .poi-item.poi").each(function() {
            if(j$(this).hasClass("poi-item-tpl")) {
                return;
            }
            var poiId = j$(this).attr("id");
            var item = j$(this).data("item");
            var wpIds = j$(this).data("photos");
            if(wpIds && wpIds.length > 0 ) {
                linkInfo.push([item.meta, item.type, poiId, wpIds]);
            }
        });
        data["link_poi_data"] = linkInfo;
        data["link_poi_count"] = linkInfo.length;
    };

    var _collectDismissedPOIs = function(data){
        if(!data["link_poi_data"]){
            return;
        }
        var dismissedInfo = [];
        var linkedWapoint = [];
        // data-dismissed=1 && .unselected
        j$("#photo-panel").find(".unselected").each(function() {
            var item = j$(this).attr("id");
            if ( j$(this).data("dismissed") === 1 ) { dismissedInfo.push([item]); }
        });
        data["dismissed_poi_data"] = dismissedInfo;
        data["dismissed_poi_count"] = dismissedInfo.length;
    };

    var _linkAlreadyLinkedPhotos = function() {
        j$(".photo-item").each(function() {
            var draggable = j$(this);
            if(!draggable.data("belongs-to-poi-id")) {
                return;
            }
            var droppable = j$("#" + draggable.data("belongs-to-poi-id"));
            var imgUrl = draggable.find(".photo img").attr("src");
            _addPhotoToPOI(droppable, draggable, imgUrl);
        });
    };

    var _selectPhoto = function ( obj ) {
        obj.toggleClass("photo-checked");
        j$("#preview-popup").hide();
        if ( obj.hasClass("photo-checked") ) {
            obj.find(".selected-icon").show();
        }else {
            obj.find(".selected-icon").hide();
        }
        _draggableFunc();
    };

    var _draggableFunc = function () {
        var _selected = j$("#photo-panel .photo-checked");
        j$("#photo-panel .photo-item").draggable({
            appendTo: "body",
            cursorAt: {right: 20, top: 20},
            cursor: "pointer",
            helper: function() {
                var _this = j$(this);
                if ( !_this.hasClass("photo-checked") ) {
                    _this.addClass("photo-checked");
                    _this.find(".selected-icon").show();
                    _selected = j$("#photo-panel .photo-checked");
                }
                var _container = j$("<ul/>").attr("id", "draggingContainer").addClass("dragging pr")
                    .append(j$("<div class='icon pa'>"+ _selected.length +"</div>"));
                var _obj = _selected.clone();
                _obj.find("img").load(function() {
                    bt.misc.centerAlignImg(j$(this), 40, 60, false);
                });
                bt.misc.centerAlignImg(_obj.find("img"), 40, 60, false);
                _container.append(_obj).find(".selected-icon").remove();
                _container.find(".photo-item").not(":eq(0)").hide();
                return _container;
            },
            revert: "invalid",
            start: function(e, ui) {
                j$("#preview-popup").stop(true, true).hide().addClass("hidden");
                $.each(_selected, function(index, val) {
                    j$(val).addClass("dragged");
                });
            },
            stop: function(e, ui) {
                $.each(_selected, function(index, val) {
                    j$(val).removeClass("dragged");
                });
            }
        });
    };


    j$(document).ready(function() {
        bt.misc.initInputPlaceholder();

        j$(".photo-panel .photo-item img").each(function() {
            bt.misc.centerAlignImg(j$(this), 146, 146, false);
        });

        j$(".photo-panel .photo-item img").load(function() {
            bt.misc.centerAlignImg(j$(this), 146, 146, false);
        });

        poiScroller = new ScrollPanel(".poi-panel", ".poi-list",
            {itemSize: 130, displayCount: 6}).navigator(".navi");
        poiScroller.addItem(j$(".poi-panel .poi-list .poi-item").length - 1);

        j$(".poi-panel .poi-item.poi").each(function() {
            if(j$(this).hasClass("poi-item-tpl")) {
                return;
            }
            ellipsisPOI(j$(this));
            j$(this).data("item", {
                meta: j$(this).data("item-meta"),
                type: j$(this).data("item-type"),
                lat: j$(this).data("lat"),
                lng: j$(this).data("lng")
            });
        });

        j$("#photo-panel .photo-item").on('click', function(e) {
            var _self = $(this);
            if(e.shiftKey) {
                _self.prevUntil('.photo-checked').filter('.unselected').each(function(i, el) {
                    _selectPhoto($(el));
                });
            }
            _selectPhoto(_self);
        });

        _draggableFunc();

        _initPOIEvent(j$(".poi-panel .poi-item.poi"));

        j$(".photo-item .photo").on("mousemove", function(e) {
            var arrow = j$("#preview-popup").find(".arrow");
            arrow.css("top", e.pageY - 152);
        });

        j$(".photo-item .photo").on("mouseout", function() {
            j$("#preview-popup").hide();
        });

        j$(".photo-panel .photo-item .photo").on("hover", function(e) {
            var popup = j$("#preview-popup");
            if ( j$(this).parent("li").hasClass("photo-checked") ) {
                return false;
            }
            if(e.type == "mouseenter") {
                var left = j$(".photos .unselected")
                    .index(j$(this).parents(".photo-item")) % 6 < 3;
                popup.removeClass("left right")
                    .addClass(left? "left": "right")
                    .css("left", j$(this).offset().left + (left? 152: -399));
                popup.find(".photo-wrapper").css({
                    "height": j$(this).data("photo-h"),
                    "width": j$(this).data("photo-w")
                });

                popup.find(".text .ellipsis_text").html(j$(this).find(".text").html());
                popup.find(".text").addClass("invisible");
                var img = popup.find("img").attr("src", j$(this).data("photo"));
                bt.misc.centerAlignImg(img, 311, 371, true);
                img.load(function() {
                    bt.misc.centerAlignImg(j$(this), 311, 371, true);
                });
                popup.stop(true, true).delay(800).fadeIn(200, function() {
                    popup.removeClass("hidden");
                    popup.find(".text").removeAttr('threedots');
                    popup.find(".text .threedots_ellipsis").remove();
                    popup.find(".text").ThreeDots({max_rows: 3});
                    if(popup.find(".text").attr("threedots")) {
                        popup.find(".text").removeClass("invisible");
                    }
                });
            } else {
                popup.stop(true, true).fadeOut(100);
                popup.addClass("hidden");
            }
        });

        j$(".poi-panel .new-poi[rel]").overlay({
            mask: {color: '#000000', loadSpeed: 200, opacity: 0.5}
        });

        initAddPOIPopupEvent();

        j$("#poi-view-popup .photo-item .remove").live("click", function() {
            var photoItem = j$(this).parents(".photo-item");
            photoItem.fadeOut().addClass("to-remove");
            if(j$("#poi-view-popup .content ul li").length
                - j$("#poi-view-popup .content .to-remove").length == 0) {
                j$("#poi-view-popup .content ul").addClass('empty');
            } else {
                j$("#poi-view-popup .content ul").removeClass('empty');
            }
        });

        j$("#poi-view-popup .done").live("click", function() {
            j$("#poi-view-popup .photo-item.to-remove").each(function() {
                var id = j$(this).data("wp-id");
                j$(this).remove();
                j$("#" + id).fadeIn().addClass("unselected").attr('data-dismissed', 1);
                _checkAllPhotosLinkedToPOI();
                var imgUrl = j$("#poi-view-popup img").last().attr("src") || false;
                if(imgUrl) {
                    j$(".viewing .default-image img").attr("src", imgUrl);
                } else {
                    j$(".viewing .default-image img").remove();
                }
                var photos = j$(".viewing").data("photos");
                photos.splice(j$.inArray(id, photos), 1);
                _updateLinkedPhotoCount(j$(".viewing"));
            });

            j$("#poi-view-popup").dialog("close");
        });

        j$(".poi-list .poi-item.poi .default-image").live("click", function(e) {
            var poi = j$(this).parents(".poi-item.poi");
            var photos = poi.data("photos");
            j$("#poi-view-popup .content ul").empty();
            poi.addClass("viewing");
            for(var p in photos) {
                var newItem = j$("<li class='photo-item fl pr'>"
                    + "<div class='photo'></div>"
                    + "<div class='remove pa hidden'></div>"
                    + "</li>");
                j$("#" + photos[p] + " .photo img").clone()
                    .appendTo(newItem.find(".photo"));
                newItem.data("wp-id", photos[p])
                    .appendTo("#poi-view-popup .content ul");
            }

            j$("#poi-view-popup").dialog({
                closeText: "",
                modal: true,
                width: 482,
                position: "center",
                close: function(e, ui) {
                    j$(".viewing").removeClass("viewing");
                    j$("#poi-view-popup .icon").attr("class", "icon fl");
                }
            });
            j$("#poi-view-popup .close").click(function(e) {
                j$("#poi-view-popup").dialog("close");
            });
            var dialog = j$("#poi-view-popup").dialog("widget");

            dialog.find(".photo img").load(function() {
                bt.misc.centerAlignImg(j$(this), 140, 140, false);
            });
            bt.misc.centerAlignImg(dialog.find(".photo img"), 140, 140, false);

            dialog.find(".title .icon")
                .addClass(poi.data("type"));

            dialog.find(".title .threedots_ellipsis").remove();

            dialog.find(".title .poi-name span")
                .text(poi.find(".title .text").attr("threedots"));
            dialog.find(".title .poi-name").removeAttr("threedots")
                .ThreeDots({max_rows: 1, whole_word: false, allow_dangle: true});

            var address = j$.trim(poi.data("address"));
            if(address && address != "位置" && address != "添加位置") {
                dialog.find(".title .poi-address").show();
                dialog.find(".title .poi-address").css("max-width",
                        352 - j$("#poi-view-popup .title .poi-name").outerWidth());
                dialog.find(".title .poi-address span")
                    .text(poi.data("address"));
                dialog.find(".title .poi-address").removeAttr("threedots")
                    .ThreeDots({max_rows: 1, whole_word: false, allow_dangle: true});
            } else {
                dialog.find(".title .poi-address").hide();
                dialog.find(".title .poi-address span").text("");
                dialog.find(".title .poi-address").removeAttr("threedots");
            }

            if(j$("#poi-view-popup .content ul li").length == 0) {
                dialog.find(".content ul").addClass('empty');
            } else {
                dialog.find(".content ul").removeClass('empty');
            }
        });

        initEditPOIPopupEvent();

        j$(".poi-list .poi-item.poi .title").live("click", function(e) {
            var poi = j$(this).parents(".poi-item.poi");
            currentPOI = poi;
            var name = poi.find(".title .text").attr("threedots");
            var address = j$.trim(poi.data("address"));

            poi.addClass("editing");
            editMap.bteditable = poi.hasClass("is-new-poi");

            j$("#poi-edit-popup").dialog({
                closeText: "",
                modal: true,
                width: 491,
                position: "center",
                close: function(e, ui) {
                    j$(".editing").removeClass("editing");
                    j$("#poi-edit-popup .icon").attr("class", "icon fl");
                    if(marker) {
                        marker.setMap(null);
                        marker = null;
                    }
                }
            });
            j$("#poi-edit-popup .close").click(function(e) {
                j$("#poi-edit-popup").dialog("close");
            });

            var dialog = j$("#poi-edit-popup").dialog("widget");
            dialog.find(".title .icon").addClass(poi.data("type"));
            if(editMap.bteditable) {
                dialog.find(".title .poi-name").addClass("editable");
                dialog.find(".title input").show();
                dialog.find(".title span").hide();
                dialog.find(".title input").val(name);
            } else {
                dialog.find(".title .poi-name").removeClass("editable");
                dialog.find(".title input").hide();
                dialog.find(".title span").show();

                dialog.find(".title .threedots_ellipsis").remove();
                dialog.find(".title .poi-name span").text(name);
                dialog.find(".title .poi-name").removeAttr("threedots")
                    .ThreeDots({max_rows: 1, whole_word: false, allow_dangle: true});
            }
            dialog.find(".map-edit .location .text .threedots_ellipsis").remove();
            dialog.find(".map-edit .location .text .ellipsis_text").text(poi.data("address"));
            dialog.find(".map-edit .location .text").removeAttr("threedots")
                .ThreeDots({max_rows: 1, whole_word: false, allow_dangle: true});

            bt.gmap.refreshMap(editMap);
            var info = poi.data("item");
            if(info.lat && info.lng) {
                bt.gmap.setZoom(editMap, 13);
                bt.gmap.panTo(editMap, info.lat, info.lng);
                _addMarker(info.lat, info.lng, editMap,
                           j$("#poi-edit-popup .map-edit"),
                           _saveEditingPOI);
            } else {
                marker = null;
                bt.gmap.zoomToWorld(editMap);
            }
        });

        j$(".poi-list .poi-item .remove").live("click", function(e) {
            var poiItem = j$(this).parents(".poi-item");
            if(confirm("真的要删除这个拍照地点么？")) {
                var photos = poiItem.data("photos");
                for(var i in photos) {
                    j$("#" + photos[i]).fadeIn().addClass("unselected").attr("data-dismissed", 1);
                }
                _checkAllPhotosLinkedToPOI();
                poiItem.fadeOut(function() {
                    j$(this).remove();
                    poiScroller.removeItem();
                });
            }
            e.stopPropagation();
        });

        j$(".buttons .next").click(function() {
            if ( j$(this).hasClass('button-disable') ) { return false; }
            j$(this).next('p').show();
            j$(this).addClass('button-disable');
            var data = bt.misc.initPostData();
            _collectNewPOIs(data);
            _collectLinkInfo(data);
            _collectDismissedPOIs(data);
            j$.ajax({
                type: "POST",
                url: location.href,
                data: j$.param(data),
                success: function(resp) {
                    window.location.href = resp.redirect_url;
                },
                error: function(resp) {
                    j$(this).removeClass('button-disable');
                    // j$(this).next(p).text(resp);
                    //alert();
                    bt.misc.alertGeneralError();
                }
            });
        });

        // link those already linked photos
        _linkAlreadyLinkedPhotos();
    });
}});

